#' Calculates crime rate per X residents.
#'
#'@param df dataframe. Dataframe that includes grouping variables
#'and crime col.
#'@param per numeric. # of residents to quantify the rate
#'(e.g. crimes per 10,000 or crimes per 100,000).
#'@param crime_col character. Name of the column in df for which
#'the rate should be calculated.
#'@param population_col character. Name of column in df to use as
#'the population.
#'@param grouping_vars vector. Column(s) to use as ID variables
#'for calculating rate.
#'@param window integer. The number of incremental years across
#'which to calculate the rate (e.g. 5 would be calculating the
#'crime rate in 5-year increments).
#'
#'@return df with "crime_rate" column
#'@export
.calc_crime_rate <- function(df, per, crime_col, population_col, grouping_vars=c(),
                             window=NULL) {

  if (is.null(window)) {

    rates <- df %>%
      group_by_at(grouping_vars) %>%
      summarize(crime_rate = (sum(!!sym(crime_col))/sum(!!sym(population_col)))*per) %>%
      ungroup()


  } else {

    out <- df %>%
      arrange(year) %>%
      mutate(end_year = ifelse(year %% window == 0, year, NA),
             end_year = ifelse(year==1965, 1970, end_year)) %>%
      group_by_at(grouping_vars) %>%
      fill(end_year, .direction="up") %>%
      group_by_at(append(grouping_vars, "end_year")) %>%
      mutate(n_rows = n()) %>%
      filter(n_rows >= window) %>%
      select(-n_rows) %>%
      ungroup()


    rates <- out %>%
      group_by_at(append(grouping_vars, "end_year")) %>%
      summarize(crime_rate = (sum(!!sym(crime_col))/sum(!!sym(population_col)))*per,
             crimes_in_window = sum(!!sym(crime_col))) %>%
      ungroup()
  }

  return(rates)
}
